package com.logback.mvc;

import com.logback.basic.ResponseData;
import com.logback.filter.TrackIdFilter;
import org.slf4j.MDC;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.util.Objects;

/**
 * @author chenfoxin
 * @Description 自定义返回值处理器
 * @Date 2022/6/8 7:58
 **/
public class ResponseReturnValueHandler implements HandlerMethodReturnValueHandler {
    private RequestResponseBodyMethodProcessor target;

    public ResponseReturnValueHandler(RequestResponseBodyMethodProcessor target) {
        this.target = target;
    }
    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return target.supportsReturnType(returnType);
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        if(Objects.nonNull(returnType) && returnValue instanceof ResponseData){
            ResponseData responseData = (ResponseData) returnValue;
            responseData.setTraceId(MDC.get(TrackIdFilter.UNIQUE_ID_NAME));
        }
        target.handleReturnValue(returnValue,returnType,mavContainer,webRequest);
    }
}
